package main

import (
	"context"
  "os"
  "os/signal"
  "net/http"
  "time"
  "syscall"
  "log"

  "gitee.com/Liaojx/ngx_auth_request_ldap_server/app"
)

func main() {
  sigint := make(chan os.Signal, 1)
  signal.Notify(sigint, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
  defer close(sigint)
  defer signal.Stop(sigint)

  App := app.App
  mux := http.NewServeMux()
  mux.HandleFunc("/", App.LdapAuth)
  mux.HandleFunc("/reload", App.Reload)
  srv := &http.Server{
    Addr: ":8000",
    Handler: mux,
    ReadTimeout: 10 * time.Second,
    ReadHeaderTimeout: 5 * time.Second,
    MaxHeaderBytes: 4096,
  }

  log.Printf("Server startup %s\n", srv.Addr)
  log.Println("pid is", os.Getpid())

  go func(){
    if err := srv.ListenAndServe(); err != nil {
      if err.Error() != "http: Server closed" {
        log.Fatalln(err)
      } else {
        log.Println("Server closed")
      }
    }
  }()

  for {
    select {
      case <-sigint: {
        if err := srv.Shutdown(context.Background()); err != nil {
          log.Println(err)
        }
        return
      }
      default: {
        time.Sleep(500 * time.Millisecond)
      }
    }
  }
}
